package close.mazegame.entity.effect;


import java.util.Random;

import com.badlogic.gdx.graphics.g2d.TextureRegion;
import com.badlogic.gdx.math.Vector2;

import close.mazegame.art.EffectTextures;
import close.mazegame.entity.Entity;
import close.mazegame.level.Level;

public abstract class Effect extends Entity {
	
	protected static final Random random = new Random();
	protected float angle;
	
	protected Vector2 position;
	protected Vector2 velocity;
	
	protected final EffectTextures textures;
	
	protected float animationTime = 0;
	protected final float frameDuration;
	protected final float animationDuration;
	protected final boolean loop;

	public Effect(Vector2 position, Level level, EffectTextures textures, float frameDuration, boolean loop) {
		super(level);
		this.position = new Vector2(position);
		this.velocity = new Vector2();
		this.textures = textures;
		this.mainTexture = textures.getTexture(0);
		this.frameDuration = frameDuration;
		this.animationDuration = textures.getNTextures() * frameDuration;
		this.loop = loop;
		angle = (float) (random.nextFloat() * 2.0f * Math.PI);
	}

	@Override
	public float getX() {
		return position.x;
	}

	@Override
	public float getY() {
		return position.y;
	}
	
	@Override
	public float getAngle() {
		return angle;
	}

	@Override
	public void update(float delta) {
		
		position.x += velocity.x * delta;
		position.y += velocity.y * delta;
		
		animationTime += delta;
		if (animationTime >= animationDuration) {
			if (loop) {
				while(animationTime >= animationDuration) {
					animationTime -= animationDuration;
				}
			} else {
				this.remove();
				return;
			}
		}
		mainTexture = getCurrentTexture();
	}
	
	public TextureRegion getCurrentTexture() {
		int frameNumber = (int)(animationTime / frameDuration);
		return textures.getTexture(frameNumber);
	}
	
	public float getAnimationFraction() {
		return animationTime / animationDuration;
	}
	
	protected void setVelocity(float speed, float direction) {
		velocity.x = (float) (Math.cos(Math.toRadians(direction)) * speed);
		velocity.y = (float) (Math.sin(Math.toRadians(direction)) * speed);
	}

}
